package com.xie.wechat;

import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

import com.google.gson.Gson;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.io.InputStream;
import java.util.concurrent.TimeUnit;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class RegisterActivity extends AppCompatActivity {
    private String registerUrl = "http://10.23.34.211:3000/api/user/account/register/";
    private EditText edit_name, edit_psd,edit_again_psd;//用户名和密码的文本输入框
    private Button btn_register;//登录按钮
    public final static int CONNECT_TIMEOUT = 60;
    public final static int READ_TIMEOUT = 100;
    public final static int WRITE_TIMEOUT = 60;
    public final static String BASE_URL="http://10.23.34.211:3000/";
    public final OkHttpClient client = new OkHttpClient.Builder()
            .readTimeout(READ_TIMEOUT, TimeUnit.SECONDS)// 设置读取超时时间
            .writeTimeout(WRITE_TIMEOUT, TimeUnit.SECONDS)// 设置写的超时时间
            .connectTimeout(CONNECT_TIMEOUT, TimeUnit.SECONDS)// 设置连接超时时间
            .build();
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_register);
        initView(); // 初始化数据
    }

    private void initView() {
        edit_name = (EditText) findViewById(R.id.register_name);
        edit_psd = (EditText) findViewById(R.id.register_password);
        edit_again_psd = (EditText) findViewById(R.id.register_again_password);
        btn_register = (Button) findViewById(R.id.btn_register);




        btn_register.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String username = edit_name.getText().toString().trim();
                String password = edit_psd.getText().toString().trim();
                String confirmedPassword = edit_again_psd.getText().toString().trim();
                // 输入框判空
                if (username.isEmpty() || password.isEmpty()) {
                    Toast.makeText(RegisterActivity.this, "用户名/密码不能为空", Toast.LENGTH_SHORT).show();
                } else {
                    register(username, password,confirmedPassword);
                }
//                // Intent 去设置要跳转的页面
//                Intent intent = new Intent(LoginActivity.this, RegisterActivity.class);
//                // 进行跳转
//                startActivity(intent);
//
//                finish();
            }
        });
    }


    private void register(String username, String password,String confirmedPassword) {

        // 账号密码转为Json格式传给后台
        MediaType JSON = MediaType.parse("application/json; charset=utf-8");
        // 将要传的参数保存进Json对象
        JSONObject jsJson = new JSONObject();
        try {
            jsJson.put("username", username);
            jsJson.put("password", password);
            jsJson.put("confirmedPassword", confirmedPassword);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        Log.d("111111 jsJson ====", ":" + jsJson);

        // 1 . 拿到OkHttpClient对象
//        OkHttpClient client = new OkHttpClient();
        // 创建一个RequestBody(参数1：数据类型 参数2传递的json串)
        RequestBody requestBody = RequestBody.create(JSON, String.valueOf(jsJson));
        Log.d("111111 requestBody ====", ":" + requestBody);

// "token": "eyJhbGciOiJIUzI1NiJ9.eyJqdGkiOiI0ZWE0Y2IyMjdkYTk0ZjU2YmU3ZTM3OGM3NzQ3Y2NkNCIsInN1YiI6IjEiLCJpc3MiOiJzZyIsImlhdCI6MTY2OTA4NTU0NywiZXhwIjoxNjcwMjk1MTQ3fQ.iL4DD6rZkS6Gg5OGhznCkXnGzjo8LEcb1RyS6g-WJGM"
        // 3 . 构建Request,将FormBody作为Post方法的参数传入
        Request request = new Request.Builder()
                .url(registerUrl)
                //.addHeader("token", "eyJhbGciOiJIUzI1NiJ9.eyJqdGkiOiI0ZWE0Y2IyMjdkYTk0ZjU2YmU3ZTM3OGM3NzQ3Y2NkNCIsInN1YiI6IjEiLCJpc3MiOiJzZyIsImlhdCI6MTY2OTA4NTU0NywiZXhwIjoxNjcwMjk1MTQ3fQ.iL4DD6rZkS6Gg5OGhznCkXnGzjo8LEcb1RyS6g-WJGM")
                //.addHeader("Authorization", "Bearer eyJhbGciOiJIUzI1NiJ9.eyJqdGkiOiI0ZWE0Y2IyMjdkYTk0ZjU2YmU3ZTM3OGM3NzQ3Y2NkNCIsInN1YiI6IjEiLCJpc3MiOiJzZyIsImlhdCI6MTY2OTA4NTU0NywiZXhwIjoxNjcwMjk1MTQ3fQ.iL4DD6rZkS6Gg5OGhznCkXnGzjo8LEcb1RyS6g-WJGM")
                .addHeader("Content-Type", "application/json;charset=UTF-8")
                //.addHeader("Origin","*")
                //.addHeader("Access-Control-Request-Headers","*")
                .post(requestBody)
                .build();
//        Request request = new Request.Builder()
//                .url(loginUrl2)
//                .addHeader("Authorization", "Bearer eyJhbGciOiJIUzI1NiJ9.eyJqdGkiOiI0ZWE0Y2IyMjdkYTk0ZjU2YmU3ZTM3OGM3NzQ3Y2NkNCIsInN1YiI6IjEiLCJpc3MiOiJzZyIsImlhdCI6MTY2OTA4NTU0NywiZXhwIjoxNjcwMjk1MTQ3fQ.iL4DD6rZkS6Gg5OGhznCkXnGzjo8LEcb1RyS6g-WJGM")
//                //.addHeader("Authorization", "Bearer eyJhbGciOiJIUzUxMiJ9.eyJ1c2VyX2lkIjoxLCJ1c2VyX2tleSI6IjQzM2Y3ZWE4LTZiMDctNGRjNy04ODYzLTE4OTgxNDgxOGY2NCIsInVzZXJuYW1lIjoiYWRtaW4ifQ.rPkJDV85kZ44c7-WzH-1Ncsd2_WIQgfbh7QmUNJ6hH2DzKr4GZ6PICgLJhPzVbYdONy5xubsNv2QXLXcIaU4hg")
////                .addHeader("Content-Type", "application/json;charset=UTF-8")
////                .addHeader("Access-Control-Allow-Credentials","true")
//                .get()
//                .build();
        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Log.d("111111 post 请求失败 ======", "e.getMessage()" + e.getMessage());
                Log.d("111111 post 请求失败 ======", "e.request()" + call.request());
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                // 请求成功返回结果
                // 如果希望返回的是字符串
                final String responseData = response.body().string();
                // 如果希望返回的是inputStream,有inputStream我们就可以通过IO的方式写文件.
                InputStream responseStream = response.body().byteStream();
                // 注意，此时的线程不是ui线程，
                // 如果此时我们要用返回的数据进行ui更新，操作控件，就要使用相关方法

                Log.d("111111 post 请求成功 ===", "responseData >>" + responseData);
                Log.d("111111 post 请求成功 ===", "responseStream >>" + responseStream);

                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {


                        // Intent 去设置要跳转的页面
                        Intent intent = new Intent(RegisterActivity.this, LoginActivity.class);
                        // 进行跳转
                        startActivity(intent);

                        finish();
                    }
                });

            }
        });

    }
}
